package org.example.course.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.example.commonapi.domain.*;
import org.example.commonapi.dto.*;
import org.example.commonapi.util.JwtUtil;
import org.example.commonapi.util.TimeUtil;
import org.example.course.service.*;
import org.example.course.until.CourseUntil;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static org.example.commonapi.domain.Constants.*;

/**
 * @author XieNoDesire
 * @Description 课程管理控制层
 */
@RestController
@RequestMapping("/course")
@Slf4j
public class CourseController {

    @Resource
    private CourseService courseService;

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private CourseAssignmentsService courseAssignmentsService;

    @Resource
    private CourseExamsService courseExamsService;

    @Resource
    private TaskService taskService;




    /**
     * 学生查询参与的教育课堂
     * @return
     */
    @GetMapping("/studentlist")
    public R list(@RequestParam(defaultValue = "1")Integer pageNum,@RequestParam(defaultValue = "8")Integer pageSize,Integer state, String courseName, HttpServletRequest request) {
        LoginInfo loginInfo =jwtUtil.parseJwt(request.getHeader("token"));
        PageInfo list=courseService.studentList(pageNum,pageSize,state,courseName,loginInfo.getId());
        log.info("课程列表：{}",list);
        return R.success(list);
    }

    /**
     * 老师查询自己创建的教育课堂
     * @param state
     * @param courseName
     * @param request
     * @return
     */
    @GetMapping("/teacherlist")
    public R teacherList(@RequestParam(defaultValue = "1")Integer pageNum,@RequestParam(defaultValue = "8")Integer pageSize, Integer state, String courseName, HttpServletRequest request) {
        LoginInfo loginInfo =jwtUtil.parseJwt(request.getHeader("token"));
        PageInfo list=courseService.teacherList(pageNum,pageSize,state,courseName,loginInfo.getId());
        log.info("课程列表：{}",list);
        return R.success(list);
    }


    /**
     * 查询所有教学课堂（其实暂时没啥鸟用，先放着）
     * @param state
     * @param courseName
     * @return
     */
    @GetMapping("/publiclist")
    public R publicList(Integer state, String courseName) {
        List<CourseInfoDto> list=courseService.list(state,courseName);
        log.info("所有课程列表：{}",list);
        return R.success(list);
    }

    /**
     * 老师创建课程
     * @param course
     * @param request
     * @return
     */
    @PostMapping("/insert")
    public R insertCourse(@RequestBody Course course, HttpServletRequest request) {
//        判断课程是否合法
        log.info("课程添加：{}",course);
        R result= CourseUntil.isCourse(course);
        if(result!=null)return result;
//        解析出id
        LoginInfo loginInfo =jwtUtil.parseJwt(request.getHeader("token"));
//        对课程进行添加
        courseService.insertCourse(course,loginInfo.getId());
        log.info("课程添加成功：{}",course);
        return R.success();
    }

    /**
     * 修改课程简介/内容/状态（老师）
     * @param course
     * @return
     */
    @PutMapping("/update")
    public R updateCourse(@RequestBody Course course) {
//        判断课程是否合法
        R result= CourseUntil.isCourse(course);
        if(result!=null)return result;
        courseService.updateById(course);
        return R.success();
    }

    /**
     * 老师删除课程（只单个删除）
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public R deleteCourse(@PathVariable("id") Long id) {
        courseService.removeById(id);
        return R.success();
    }

    /**
     * 全部更新状态接口
     * @return
     */
    @PutMapping("/update/state")
    public R updateCourseState() {
        LocalDateTime now=LocalDateTime.now();
        List<Course> list=courseService.list();
        for (Course course:list){
            boolean isUpdate=false;
            //未开始
            if(TimeUtil.compareTime(now,course.getStartTime())){
                if(course.getState()==null||!course.getState().equals(NO_Start_State)) {
                    course.setState(NO_Start_State);
                    isUpdate=true;
                }
            }
//           开始
            else if (TimeUtil.compareTime(course.getStartTime(),now)&&TimeUtil.compareTime(now,course.getEndTime())){
                if(course.getState()==null||!course.getState().equals(Start_State)){
                    course.setState(Start_State);
                    isUpdate=true;
                }
            }
//            结束
            else if (TimeUtil.compareTime(course.getEndTime(),now)){
                if(course.getState()==null||!course.getState().equals(End_State)){
                    course.setState(End_State);
                    isUpdate=true;
                }
            }
//            如果改变了
            if(isUpdate){
                courseService.updateById(course);
                isUpdate=false;
            }
        }
        return R.success();
    }


    /**
     * 更新课程人数
     * @param courseId
     * @param number
     * @return
     */
    @PutMapping("/update/number/{courseId}")
    public R updateCourseNumber(@PathVariable("courseId") Long courseId,@RequestParam Integer number)  {
        courseService.updateCourseNumber(courseId,number);
        return R.success();
    }

    /**
     * 获取课程详情
     * @param courseId
     * @return
     */
    @GetMapping("/get/{courseId}")
    public R getCourse(@PathVariable("courseId") Long courseId) {
        Course course=courseService.getById(courseId);
        return R.success(course);
    }

    /**
     * todo 查看课程情况，分别查看（作业，任务，考试）
     * @param courseId
     * @param type
     * @return
     */
    @GetMapping("/list/course/detail/{courseId}")
    public R listCourseDetail(@PathVariable Long courseId,Integer type){
//        作业查询完成率
        if(Objects.equals(type, Assignment_TYPE)){
            List<AssignmentFinish> list=courseAssignmentsService.listAssignmentDetail(courseId);
            return R.success(list);
        }
//        任务查询完成的人数
        else if(Objects.equals(type, Task_TYPE)){
           List<TaskFinish>list= taskService.listTaskDetail(courseId);
           return R.success(list);
        }
//        考试查询谁没做,平均分
        else if(Objects.equals(type, Exam_TYPE)){
            List<ExamFinish> list=courseExamsService.listExamDetail(courseId);
        }
        return R.success();
    }

    /**
     * 根据课程id查询课程信息
     * @param courseId
     * @return
     */
    @GetMapping("/getCourseInfoById")
    public R<Course> getCourseInfoById(@RequestParam Long courseId){
        return R.success(courseService.getById(courseId));
    }

}
